package pri.hillchen.std.concurrent.chapter14.boundedbuffer;

import java.util.concurrent.TimeUnit;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 10:28 2018/2/1 0013.
 */
public class SleepBoundedBuffer<V> extends BaseBoundedBuffer<V> {
    public SleepBoundedBuffer(int capacity) {
        super(capacity);
    }
    public  void put(V ele) throws  InterruptedException {
        while (true){
            synchronized (this){
                if(!isFull()){
                    doPut(ele);
                    return;
                }
            }
            TimeUnit.NANOSECONDS.sleep(1);
        }

    }

    public  V take() throws InterruptedException {
        while (true){
            synchronized (this){
                if(!isEmpty()){
                    return doTake();
                }
            }
            TimeUnit.NANOSECONDS.sleep(1);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SleepBoundedBuffer<Integer> boundedBuffer = new SleepBoundedBuffer<>(10);
        for(int i = 0; i<10;i++){
            boundedBuffer.put(i);
        }
        for(int i = 0; i<10;i++){
            System.out.println(boundedBuffer.take());
        }
    }
}
